import os

from sqlalchemy import create_engine, Column, String, Integer, DateTime, Text
from sqlalchemy.orm import sessionmaker, declarative_base  # 使用 sqlalchmey.orm.declarative_base
from config import DATABASE_URL
import logging

# 设置日志
if not logging.getLogger().hasHandlers():  # 如果未设置全局日志处理器，单独运行时初始化日志
    os.makedirs("logs", exist_ok=True)  # 确保日志目录存在
    logging.basicConfig(
        level=logging.INFO,  # 设置日志级别
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        handlers=[
            logging.FileHandler('logs/initialize_db.log'),  # 写入到独立日志文件
            logging.StreamHandler()  # 同时输出到控制台
        ]
    )

logger = logging.getLogger(__name__)

# 创建Base类
Base = declarative_base()

# 定义表结构
class Quote(Base):
    __tablename__ = 'quotes'

    id = Column(Integer, primary_key=True, autoincrement=True)
    content = Column(String(500), nullable=False)
    author = Column(String(100), nullable=True)
    source = Column(String(200), nullable=True)
    uuid = Column(String(100), nullable=True)
    created_at = Column(DateTime, nullable=True)

class Plot(Base):
    __tablename__ = 'plots'

    id = Column(Integer, primary_key=True, autoincrement=True)
    title = Column(String(255), nullable=False)  # 新增 title 字段
    content = Column(Text, nullable=False)  # 修改为 Text 类型，支持更长的内容
    previous_chapter_id = Column(Integer, nullable=True)
    created_at = Column(DateTime, nullable=True)

# 数据库连接
engine = create_engine(DATABASE_URL)

# 创建表
def initialize_db():
    try:
        # 删除所有表
        Base.metadata.drop_all(engine)
        logger.info("All tables dropped successfully.")

        # 创建表结构
        Base.metadata.create_all(engine)
        logger.info("Database tables created successfully.")
    except Exception as e:
        logger.error(f"Error creating tables: {e}")

if __name__ == "__main__":
    initialize_db()
